<?php
namespace app\api\controller\v1;
use app\api\controller\Api;
use app\sns\validate\ValidataCommon;
use data\extend\Aes;
use data\extend\ErrCode;
use data\service\PicFilesService;
use data\service\PicUserService;
use think\Exception;
use think\Request;
use Volc\Service\Visual;

class PicApi extends Api {

    protected $noAuth = ['index','picLogin'];
    protected $uid = 0;
    protected $openid = "";

    public function __construct(Request $request){
        parent::__construct($request);
        try {
            $post = $this->request->post('');
            @ksort($post);
            $authorization = \think\facade\Request::header('authorization');   //获取请求中的authorization字段
            $authorizationInfo  = base64_decode($authorization);  //对base_64解密

            //获取当前时间戳
            $microTime =  getMillisecond() - $post['_t'];
            //接口10分钟有效
            if($microTime >= 600000){
                return self::returnMsg(ErrCode::$IllegalInterface,'The interface has expired',[]);
            }
            $queryStr = "";
            foreach($post as $k => $v){$queryStr .= $k .'=' .$v .'&';}

            $sign = md5(Aes::aesEn(rtrim($queryStr, "&")));

            if($sign != $authorizationInfo){
                return self::returnMsg(ErrCode::$IllegalAuthorization,'Invalid authorization credentials1',[]);
            }
            $token = \think\facade\Request::header('token');   //获取请求中的authorization字段
            if($token != ""){
                $userInfo = explode('-',Aes::aesDe($token));
                $this->uid = $userInfo[0];
                $this->openid = $userInfo[1];
            }

        } catch (Exception $e) {
            return self::returnMsg(ErrCode::$IllegalAuthorization,'Invalid authorization credentials2',[]);
        }
    }


    public function picLogin(Request $request){
        if($request->isPost()){
            ValidataCommon::validateCheck([
                'avatarUrl' => 'require',
                'code' => 'require',
                'city' => 'require',
                'country' => 'require',
                'gender' => 'require',
                'nickName' => 'require',
                'province' => 'require'
            ], $request->param('')); //参数验证

            $code = $request->post('code',"");
            $nickName = $request->post('nickName',"");
            $country = $request->post('country',"");
            $province = $request->post('province',"");
            $city = $request->post('city',"");
            $avatarUrl = $request->post('avatarUrl',"");
            $gender = $request->post('gender',"");
            $uid = 0;
            $picUserService = new PicUserService();

            //通过code 获取 session_key 、openid
            $url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx1380826ad5bba6a0&secret=73d4c8c2d59d86b510ab1e0455ab7c47&js_code=".$code."&grant_type=authorization_code";
            $tempData = json_decode(curl_request($url),1);

            if(isset($tempData['openid'])){
                //拿到openid ，去数据库查询是否存在用户信息
                $tmpUserInfo = $picUserService->getUserInfoByOpenid($tempData['openid'],'id');
                if(empty($tmpUserInfo)){
                    $uid = $picUserService->register($tempData['openid'],base64_encode($nickName),$avatarUrl,$province,$city);
                } else {
                    $uid = $tmpUserInfo['id'];
                    //更新 登录时间

                }

                // $userInfo = $picUserService->getUserInfoByUid($uid,'*');
                //获取access_token
                $userInfo['token'] = Aes::aesEn($uid.'-'.$tempData['openid']);
                //$userInfo['lastlogin'] = H::time_tran($userInfo['lastlogin']);

                return self::returnMsg(ErrCode::$OK,'success',$userInfo);

            } else {
                return self::returnMsg(ErrCode::$IllegalCode,'Illegal CODE');
            }
        }
    }

    public function index(){
        if($this->request->isPost()){
            ValidataCommon::validateCheck([
                'imageUrl' => 'require',
                'type' => 'require',
                'isUrl' => 'require'
            ], $this->request->post('')); //参数验证
            $imageUrl = $this->request->post('imageUrl',"");
            $type = $this->request->post('type',0);
            $isUrl = $this->request->post('isUrl',"url");

            $base64 = "";

            if($isUrl == "base64"){
                //如果是base64，那么直接赋值到变量
                $imageData = $imageUrl;
            } else {
                //如果传过来的是
                $newImageUrl = str_replace('132','0',$imageUrl);

                $imageData = base64_encode(@file_get_contents($newImageUrl));

                // call below method if you dont set ak and sk in ～/.volc/config
            }
            //将上传的图片存储起来
            $this->downloadPics($imageData);


            $client = Visual::getInstance();
            $client->setAccessKey("AKLTNGJkMmQ3N2MyYjgxNDQ2YWEwOWFlZmNhOGQ0NDQ4MGE");
            $client->setSecretKey("Wmpaa01qQXlaREZtWkdNeE5EazVZemhoWXpKbFpESXdPVGhrTWpBNU1EZw==");

            $response = $client->JPCartoon(['form_params' => ['image_base64' => str_replace("data:image/png;base64,","",$imageData),'cartoon_type'=> $type == 2 ? 'hkcartoon':'jpcartoon']]);

            $responseArr = json_decode($response,1);

            if($responseArr['code'] == 10000){
                $base64 = "data:image/png;base64,".$responseArr['data']['image'];
            } else {
                return self::returnMsg(ErrCode::$IllegalAuthorization,$responseArr['message'],[]);
            }
            return self::returnMsg(ErrCode::$OK,'success',['image'=>$base64]);
        }

    }

    public function downloadPics( $base64 = "" ){
        $save_path =  'uploads/images/';
        $file_md5     = md5($base64);
        $file_name    = $file_md5 . ".png";
        $imgfile    = $save_path . $file_name; //保存文件名
        @file_put_contents($imgfile, $base64);
        $picFileService = new PicFilesService();
        $picFileService->register( $this->uid,$imgfile);

    }





}
